﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;

namespace JinianNet.Common
{
    public class Utils
    {
        #region GET IP
        public static string IP
        {
            get
            {
                return GetIP();
            }
        }

        public static string GetIP()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            if (context != null)
                return GetIP(context.Request);
            return GetIP(Dns.GetHostName());
        }

        public static string GetIP(string hostAddresses)
        {
            IPAddress[] arrIPAddresses = Dns.GetHostAddresses(hostAddresses);
            foreach (IPAddress ip in arrIPAddresses)
            {
                if (ip.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    return ip.ToString();
                }
            }
            return "unknown";
        }

        public static string GetIP(System.Web.HttpRequest Request)
        {
            string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
                ip = Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(ip))
                return "unknown";
            return ip;
        }

        #endregion

        #region

        public static string MD5(string key)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(key, "MD5").ToLower();
        }
        /// <summary>
        /// des加密
        /// </summary>
        /// <param name="KEYStr"></param>
        /// <param name="IVStr"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DesEncrypt(string KEYStr, string IVStr, string input)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(KEYStr);
            byte[] keyIV = Encoding.UTF8.GetBytes(IVStr); ;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(input);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Convert.ToBase64String(mStream.ToArray());

        }
        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="KEYStr"></param>
        /// <param name="IVStr"></param>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string DesDecrypt(string KEYStr, string IVStr, string input)
        {
            byte[] keyBytes = Encoding.UTF8.GetBytes(KEYStr);
            byte[] keyIV = Encoding.UTF8.GetBytes(IVStr); ;
            byte[] inputByteArray = Convert.FromBase64String(input);
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }


        /// <summary>
        /// 检查是否数字与字母的组合
        /// </summary>
        /// <param name="input">输入字符串</param>
        /// <param name="startLetter">是否必须以字母开头</param>
        /// <returns></returns>
        public static bool IsNumberOrLetter(string input,bool startLetter)
        {
            if (startLetter)
                return Regex.IsMatch(input, "^[A-Za-z]+[A-Za-z0-9]*$");
            return Regex.IsMatch(input, "^[A-Za-z0-9]+*$");
        }

        public static bool IsNumber(string input)
        {
            return Regex.IsMatch(input, @"^[\+\-]?[\d]+[\.]?[\d]?*$");
        }

        public static bool IsNumberOrLetter(string input)
        {
            return IsNumberOrLetter(input, false);
        }

        public static bool IsBase64String(string input)
        {
            return Regex.IsMatch(input, @"[A-Za-z0-9\+\/\=]");
        }

        public static bool IsNullOrEmpty(string input)
        {
            return string.IsNullOrEmpty(input) || input.Trim().Length == 0;
        }

        public static string TrimEndZero(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                if (input.LastIndexOf('.') >= 0)
                    input = input.TrimEnd('0').TrimEnd('.');
            }
            if (!string.IsNullOrEmpty(input))
                input = "0";
            return input;
        }

        public static string Replace(string input, string oldValue, string newValue)
        {
            if (string.IsNullOrEmpty(input) || oldValue == newValue)
                return input;
            while (input.Contains(oldValue))
            {
                input=input.Replace(oldValue, newValue);
            }
            return input;
        }


        /// <summary>
        /// 序列化对象，注意提交的对象必须是可序列化的，即类必须有[Serializable]标识
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] Serialize(object obj)
        {
            BinaryFormatter binaryF = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(1024 * 10);
            binaryF.Serialize(ms, obj);
            ms.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[ms.Length];
            ms.Read(buffer, 0, buffer.Length);
            ms.Close();
            return buffer;   //返回压缩后的数据
        }

        /// <summary>
        /// 反序列化对象，注意提交的对象必须是可序列化的，即类必须有[Serializable]标识
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static object Deserialize(byte[] buffer)
        {
            BinaryFormatter binaryF = new BinaryFormatter();
            MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length, false);
            ms.Seek(0, SeekOrigin.Begin);
            object obj = binaryF.Deserialize(ms);
            ms.Close();
            return obj;
        }

        #endregion
    }
}
